<script setup lang="ts">
import Tab from "@/apps/client/layout/Tab.vue";
import router from "@/apps/client/router.js";
import { ref } from "vue";
import { getUserInfo } from "@/apps/client/utils/userApi.js";
import { getHomeInfo } from "@/apps/client/utils/homeApi.js";
import { getGroupRoomsByFloor } from "@/apps/client/utils/roomApi.js";
import { getFloors } from "@/apps/client/utils/floor.js";

const swipeTops = ref([]);
const swipeBottoms = ref([]);

const htmlContent = ref("");
const notice = ref("加载中");
const homeInfo = ref({
  notice: "加载中",
  swipeTop: [],
  swipeBottom: []
});


const cards = [
  { title: '实验室\n预约', bgClass: 'bg-lab' },
  { title: '会议室\n预约', bgClass: 'bg-meeting' },
  { title: '仪器\n预约', bgClass: 'bg-instrument' },
  { title: '仪器\n借还', bgClass: 'bg-return' },
];


const pages = ["reservationSelect", "reservationSelect", "instrumentSelect", "instrumentBorrowReturn"];

// 处理底部tab切换，设置相关sessionStorage并跳转页面
function onTabChange(index) {
  sessionStorage.setItem('pageId', index);
  switch (index) {
    case 0:
      sessionStorage.setItem('selectRoomType', "LAB");
      sessionStorage.setItem('selectRoomRouteName', "cubicleReservation");
      break;
    case 1:
      sessionStorage.setItem('selectRoomType', "MEETING");
      sessionStorage.setItem('selectRoomRouteName', "cubicleReservation");
      break;
    case 2:
      sessionStorage.setItem('selectInstrumentRoutePage', "instrumentReservation");
      break;
  }
  router.push({ name: pages[index] });
}

// 获取用户信息，存入session
async function fetchUserInfo() {
  try {
    const res = await getUserInfo();
    const data = res.data;
    sessionStorage.setItem("realName", data.realName);
    sessionStorage.setItem("points", data.points);
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
}

// 获取楼层和房间分组数据，存入session
async function fetchFloorRoomData() {
  try {
    const groupRoomsRes = await getGroupRoomsByFloor();
    sessionStorage.setItem("groupRoomsByFloor", JSON.stringify(groupRoomsRes.data));

    const floorsRes = await getFloors();
    sessionStorage.setItem("floors", JSON.stringify(floorsRes.data));
  } catch (error) {
    console.error("获取楼层或房间数据失败", error);
  }
}

// 加载首页信息，优先使用session缓存
async function loadHomeInfo() {
  const cached = sessionStorage.getItem("homeInfo");
  if (cached) {
    homeInfo.value = JSON.parse(cached);
    setSwipeImages(homeInfo.value.swipeTop, homeInfo.value.swipeBottom);
  } else {
    try {
      const res = await getHomeInfo();
      homeInfo.value = res.data;
      sessionStorage.setItem("homeInfo", JSON.stringify(res.data));
      setSwipeImages(res.data.swipeTop, res.data.swipeBottom);
    } catch (error) {
      console.error("加载首页信息失败", error);
    }
  }
}

// 设置顶部和底部轮播图片地址
function setSwipeImages(swipeTopUrls = [], swipeBottomUrls = []) {
  swipeTops.value = swipeTopUrls.map(img => `/api/src/img/${img}`);
  swipeBottoms.value = swipeBottomUrls;
}

// 点击公告底部图片，跳转公告详情页
function display(item) {
  htmlContent.value = item.content;
  sessionStorage.setItem("notice", item.content);
  router.push({ name: "notice" });
}

// 组件初始化执行
fetchUserInfo();
fetchFloorRoomData();
loadHomeInfo();
</script>

<template>
  <div class="home1" style="height: 100vh;">
    <div class="home2" style="height: 100vh;">
      <van-space direction="vertical" fill style="margin: 10px; height: 100vh;">
        <van-notice-bar
            color="#1989fa"
            left-icon="volume-o"
            style="border-radius: 5px; background: #ecf9ff;"
        >
          {{ homeInfo.notice }}
        </van-notice-bar>

        <video
            :src="swipeTops[0]"
            style="width: 100%; height: 22vh; object-fit: fill; border-radius: 12px; background-color: #fff;"
            muted
            autoplay
            loop
            playsinline
            preload="auto"
            webkit-playsinline
            disablePictureInPicture
        />


        <div class="card-grid">
          <div
              v-for="(item, index) in cards"
              :key="index"
              class="card-item"
              @click="onTabChange(index)"
          >
            <div class="card-content">
              <div class="card-title">{{ item.title }}</div>
              <div class="card-icon" :class="item.bgClass"></div>
            </div>
          </div>
        </div>

        <van-swipe
            class="my-swipe"
            :autoplay="3000"
            indicator-color="white"
            style="height: 22vh; border-radius: 12px;"
        >
          <van-swipe-item
              v-for="(item, index) in swipeBottoms"
              :key="index"
          >
            <a
                @click.prevent="display(item)"
                rel="noopener noreferrer"
                style="display: block; width: 100%; height: 100%;"
            >
              <img :src="`/api/src/img/${item.img}`" alt="" style="width: 100%; height: 100%; object-fit: fill;"/>
            </a>
          </van-swipe-item>
        </van-swipe>
      </van-space>

      <Tab style="margin: 0 10px" />
    </div>
  </div>
</template>

<style scoped>
.my-swipe {
  color: #fff;
  background-color: #fff;
}

.card-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.card-item {
  background-color: white;
  border-radius: 16px;
  overflow: hidden;
  height: 12vh;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 10px;
}

.card-title {
  font-size: 1.4rem;
  white-space: pre-line;
  color: black;
  font-family: monospace;
  font-weight: 500;
  line-height: 1.4;
}

.card-icon {
  width: 50px;
  height: 50px;
  background-size: cover;
  background-position: center;
  border-radius: 12px;
}

.home1 {
  background-image: linear-gradient(
      32deg,
      #3551a4 0%,
      #2c8ec4 29%,
      #31c4cd 59%,
      #2c8ec4 100%
  );
}

.home2 {
  background-image: url('@/assets/home-bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  justify-content: space-between;
  display: flex;
  flex-direction: column;
}

.bg-lab {
  background-image: url('@/assets/icon-lab.png');
}
.bg-meeting {
  background-image: url('@/assets/icon-meeting.png');
}
.bg-instrument {
  background-image: url('@/assets/icon-instrument.png');
}
.bg-return {
  background-image: url('@/assets/icon-return.png');
}
</style>
